import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_COMMON_API,
  withCredentials: true,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
    'x-requested-with': 'XMLHttpRequest',
    'sysCode': 'csm'
  }
})

// request interceptor
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // 拦截业务性接口错误 如果success为false 表示业务性出错
    if (typeof response.data === 'string') {
      return response.data
    }
    if (response.data.success || response.data.errorCode === 1) {
      return response.data
    } else {
      message.error(response.data.errorMessage)
      return Promise.reject(response.data.errorMessage)
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })

    // 服务器抛错
    if (error.response) {
      const statusCode = error.response.status
      switch (statusCode) {
        case 400:
        case 401:
          // window.location.href = process.env.VUE_APP_ISSO_LOGOUT_URL + encodeURIComponent(window.location.href)
          break
        case 404:
        case 504:
        case 500:
          Message.error('服务器出错啦！')
          break
      }
    }

    return Promise.reject(error)
  }
)

export default service
